package cn.rkylin.oms.refund.adapter;

import cn.rkylin.oms.refund.vo.RdsRefund;
import cn.rkylin.oms.system.shop.vo.ShopVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 淘宝退款代理（负责下载解析数据存储到TOP前缀的表中）
 *
 * @author jipengcheng
 * @version 1.0
 * @created 2017.04.19
 */
@Scope("prototype")
@Service("taoBaoRefundVisitor")
public class TaoBaoRefundVisitor extends RefundVistor {
    private static final Log logger = LogFactory.getLog(TaoBaoRefundVisitor.class);
    private static final String TABLENAME = "jdp_tb_refund";

    @Override
    public List<RdsRefund>  getTopFundObject(ShopVO shop,Map<String, Object> paramMap, int startRow, int endRow) throws Exception {
        //从RDS中取得json并解析
        List<RdsRefund> list = getDataFromRds(shop,paramMap ,startRow, endRow);    //解析检索得到的json
        return list;
    }

    /**
     * 从RDS中取得json并解析
     *
     * @param paramMap
     * @param startRow
     * @param count
     * @return
     * @throws Exception
     */
    private List<RdsRefund> getDataFromRds(ShopVO shop, Map<String, Object> paramMap, int startRow, int count) throws Exception {
        if (shop == null) {
            return null;
        }
        Connection conn = null;                                     //数据库连接
        StringBuilder sql = new StringBuilder();                    //sql语句
        List<RdsRefund> list = new ArrayList<RdsRefund>();          //解析检索得到的json
        QueryRunner qr = new QueryRunner();

        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection(shop.getDbUrl(), shop.getDbUsername(), shop.getDbPassword());
        //生成SQL语句
        sql.append(" select refund_id,jdp_response");
        sql.append("  from " + TABLENAME);
        sql.append("  where seller_nick = '" + shop.getShopAccount() + "'");

        if (paramMap.containsKey("refundId") && paramMap.get("refundId") != null) {
            sql.append(" and refund_id = '" + paramMap.get("refundId") + "'");
        } else if (paramMap.containsKey("buyerNick") && paramMap.get("buyerNick") != null) {
            sql.append(" and buyer_nick like '%" + paramMap.get("buyerNick") + "%'");
        } else if (paramMap.containsKey("startTime") && paramMap.containsKey("endTime") && paramMap.get("startTime") != null && paramMap.get("endTime") != null) {
            sql.append(" and jdp_modified >= '" + paramMap.get("startTime") + "'");
            sql.append(" and jdp_modified <= '" + paramMap.get("endTime") + "'");
        }
        sql.append("LIMIT " + startRow + ", " + count);
        List<Map<String, Object>> mapLs = qr.query(conn, sql.toString(), new MapListHandler());
        for (Map<String, Object> resultmap : mapLs) {
            RdsRefund rdsRefund = getMapFromJson(resultmap.get("jdp_response").toString());
            list.add(rdsRefund);
        }

        //关闭数据库连接
        DbUtils.closeQuietly(conn);

        return list;
    }


    /**
     * 根据jdp_response进行解析形成list
     *
     * @param json
     * @return
     */
    private RdsRefund getMapFromJson(String json) {

        if (StringUtils.isBlank(json)) {
            return null;
        }

        JSONObject object = JSON.parseObject(json).getJSONObject("refund_get_response").getJSONObject("refund");
        RdsRefund rdsRefund = JSON.parseObject(object.toJSONString(), RdsRefund.class);
        return rdsRefund;

    }


}
